package com.byzk.p2p.admin.borrow.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.jsoup.helper.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.byzk.p2p.admin.admin.vo.AdminUserVo;
import com.byzk.p2p.admin.base.controller.AdminBaseController;
import com.byzk.p2p.admin.base.controller.FileController;
import com.byzk.p2p.admin.base.util.DateUtils;
import com.byzk.p2p.admin.base.util.JsonMsg;
import com.byzk.p2p.admin.base.util.PageInfo;
import com.byzk.p2p.admin.base.util.RequestUtil;
import com.byzk.p2p.admin.borrow.dto.Borrow;
import com.byzk.p2p.admin.borrow.dto.BorrowApply;
import com.byzk.p2p.admin.borrow.dto.BorrowGroup;
import com.byzk.p2p.admin.borrow.dto.BorrowGroupUser;
import com.byzk.p2p.admin.borrow.dto.Change;
import com.byzk.p2p.admin.borrow.dto.ChangeRecord;
import com.byzk.p2p.admin.borrow.dto.Product;
import com.byzk.p2p.admin.borrow.service.BorrowService;
import com.byzk.p2p.admin.borrow.service.ChangeService;
import com.byzk.p2p.admin.borrow.service.ProductService;
import com.byzk.p2p.admin.borrow.util.BorrowStatus;
import com.byzk.p2p.admin.borrow.vo.BorrowApplyVo;
import com.byzk.p2p.admin.borrow.vo.BorrowGroupUserVo;
import com.byzk.p2p.admin.borrow.vo.BorrowVo;
import com.byzk.p2p.admin.borrow.vo.ChangeVo;
import com.byzk.p2p.admin.money.service.BorrowPaymentService;
import com.byzk.p2p.admin.money.vo.BorrowPaymentVo;
import com.byzk.p2p.admin.system.service.ResourceService;
import com.byzk.p2p.admin.system.vo.ResourceVo;
import com.byzk.p2p.admin.user.dto.User;
import com.byzk.p2p.admin.user.service.UserService;
import com.byzk.p2p.admin.web.dto.Article;
import com.byzk.p2p.admin.web.service.ArticleService;

@Controller
@RequestMapping("/admin/borrow")
public class BorrowController extends AdminBaseController{

	@Autowired
	private BorrowService borrowService;
	@Autowired
	private UserService userService;
	@Autowired
	private ChangeService changeService;
	@Autowired
	private BorrowPaymentService borrowPaymentService;
	@Autowired
	private ResourceService resourceService;
	@Autowired
	private ArticleService articleService;
	@Autowired
	private ProductService productService;
	@Autowired
	private FileController fileContrller;
	
	/**
	 * 用户借款审批列表方法
	 * @param model
	 * @param index
	 * @param limit
	 * @param borrowApply
	 * @return
	 */
	@RequestMapping("/apply/list")
	public String listBorrowApply(Model model,
			   @RequestParam(value="index",required=false,defaultValue="1") int index,
			   @RequestParam(value="limit",required=false,defaultValue="10") int limit,
			   @RequestParam(value="username",required=false) String username,
				@RequestParam(value="deadline",required=false) Integer deadline,
				@RequestParam(value="status",required=false) Integer status,
				@RequestParam(value="dayline",required=false) Integer dayline){
		BorrowApplyVo borrowApplyVo = new BorrowApplyVo();
		borrowApplyVo.setIndex(index);
		borrowApplyVo.setLimit(limit);
		if (StringUtils.isNotBlank(username)) {
			borrowApplyVo.setUserName(username);
			model.addAttribute("username", username);
		}
		if (deadline != null) {
			borrowApplyVo.setDate(deadline);
			model.addAttribute("deadline", deadline);
			borrowApplyVo.setDateUtil("MONTH");
		}
		if (status != null) {
			borrowApplyVo.setStatus(status);
			model.addAttribute("status", status);
		}
		if (dayline != null) {
			borrowApplyVo.setDate(dayline);
			model.addAttribute("dayline", dayline);
			borrowApplyVo.setDateUtil("DAY");
		}
		PageInfo<BorrowApplyVo> pageInfo=borrowService.listBorrowApply(borrowApplyVo);
		model.addAttribute("pageInfo", pageInfo);
		//产品列表
		List<Product> productList = productService.productList();
		model.addAttribute("productList", productList);
		return ftl(Thread.currentThread().getStackTrace());
	}
	
	/**
	 * 用户借款 根据id 获得相关信息
	 * @param model
	 * @param id
	 * @return
	 */
	@RequestMapping("/apply/detail")
	public String showDetail(Model model,@RequestParam(value="id") Integer id){
		BorrowApplyVo borrowApply = borrowService.getBorrowApplyVo(id);
		model.addAttribute("item", borrowApply);
		//产品列表
		List<Product> productList = productService.productList();
		model.addAttribute("productList", productList);
		return ftl(Thread.currentThread().getStackTrace());
	}
	
	
	/**
	 * 新增，修改 用户借款方法
	 * @param scoreRecord
	 * @return
	 */
	@RequestMapping("/apply/save")
	public String saveBorrowApply(BorrowApply borrowApply) throws Exception{
		try {
			borrowApply.setTerminal("PC");
			Integer i = borrowService.saveOrUpdateBorrowApply(borrowApply);
			if(i>0){
				super.printJSON(new JsonMsg(-1,"操作成功",i));
			}else{
				super.printJSON(new JsonMsg(0,"操作失败",""));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 发布借款
	 * @param model
	 * @param id
	 * @return
	 */
	@RequestMapping("/add")
	public String addBorrowView(Model model,@RequestParam int id){
		BorrowApplyVo borrowApply = borrowService.getBorrowApplyVo(id);
		model.addAttribute("item", borrowApply);
		List<BorrowGroup> borrowGroups = borrowService.listBorrowGroup();
		model.addAttribute("borrowGroups", borrowGroups);
		List<Product> productList = productService.productList();
		model.addAttribute("productList", productList);
		model.addAttribute("guaranteeAll", Borrow.guaranteeAll);
		return ftl(Thread.currentThread().getStackTrace());
	}
	/**
	 * 发标
	 * */
	@RequestMapping(value="/save1",method=RequestMethod.POST)
	@ResponseBody
	public String saveBorrow1(@RequestBody Borrow borrow) throws Exception {
		try {
			if (getUserId() == null) {
				super.printJSON(new JsonMsg(0, "请先登录！"));
				return null;
			}
			if(StringUtil.isBlank(borrow.getTitle())){
				super.printJSON(new JsonMsg(1,"借款标题不能为空！"));
				return null;
			}
			if (borrow.getProductId() == null) {
				super.printJSON(new JsonMsg(1,"发标产品类型不能为空，请重新选择！"));
				return null;
			}
			/*if (StringUtils.isBlank(borrow.getBorrowUse())) {
				super.printJSON(new JsonMsg(1,"借款标用途不能为空！"));
				return null;
			}*/
			if (borrow.getAmount() == null || borrow.getAmount()<=0d) {
				super.printJSON(new JsonMsg(1,"借款金额输入错误，请重新输入！"));
				return null;
			}
			if (borrow.getAmount()%100 != 0) {
				super.printJSON(new JsonMsg(1,"借款金额输入错误，必须为100的倍数！"));
				return null;
			}
			if (borrow.getDeadline() == null) {
				super.printJSON(new JsonMsg(1,"借款期限不能为空，请重新输入！"));
				return null;
			}
			if (borrow.getPaymentMode() == null) {
				super.printJSON(new JsonMsg(1,"还款方式不能为空，请重新选择！"));
				return null;
			}
			/** 对还款方式的判断 **/
			if("DAY".equals(borrow.getDateUtil())) {
				if(borrow.getPaymentMode() != 1) {
					super.printJSON(new JsonMsg(1,"天标的还款方式能是一次性还款，请重新选择！"));
					return null;
				}
			}
			if (borrow.getPercent() == null) {
				super.printJSON(new JsonMsg(1,"借款标的年化收益率不能为空，请重新输入！"));
				return null;
			}
			/*if (borrow.getRewardPercent() != null) {
				if (borrow.getRewardPercent() >= borrow.getPercent()) {
					super.printJSON(new JsonMsg(1,"借款标的奖励年化收益率不能高于借款标的年化收益率，请重新输入！"));
					return null;
				}
			}*/
			if (borrow.getExpire() == null) {
				super.printJSON(new JsonMsg(1,"有效时间不能为空，请重新输入！"));
				return null;
			}
			/*if (StringUtils.isBlank(borrow.getAttachId())) {
				super.printJSON(new JsonMsg(1,"请上传借款标的材料！"));
				return null;
			}*/
/*			if (StringUtils.isBlank(borrow.getAptitudeAttachId())) {
				super.printJSON(new JsonMsg(1,"请上传借款标的资质审核！"));
				return null;
			}*/
			/*if (StringUtils.isBlank(borrow.getDescr())) {
				super.printJSON(new JsonMsg(1,"请输入借款标项目介绍！"));
				return null;
			}*/
			/*
			if (StringUtils.isBlank(borrow.getWindControlDetail())) {
				super.printJSON(new JsonMsg(1,"请输入风控详情！"));
				return null;
			}*/
			
			if(borrow.getGuaranteeName() == null) {
				super.printJSON(new JsonMsg(1, "请输入借款标担保方！"));
				return null;
			}
			if (StringUtils.isBlank(borrow.getPersonalInfo())) {
				super.printJSON(new JsonMsg(1,"请上传个人信息！"));
				return null;
			}
			if (StringUtils.isBlank(borrow.getCapitalInfo())) {
				super.printJSON(new JsonMsg(1,"请上传资产信息！"));
				return null;
			}
			if (StringUtils.isBlank(borrow.getBorrowDetail())) {
				super.printJSON(new JsonMsg(1,"请输入借款标借入详情！"));
				return null;
			}
			if (StringUtils.isBlank(borrow.getCapitalVoucher())) {
				super.printJSON(new JsonMsg(1,"请输入借款标资产凭证！"));
				return null;
			}
			if(borrow.getTimingShow() != null && borrow.getTimingShow().getTime()<new Date().getTime()) {
				super.printJSON(new JsonMsg(1,"定时显示时间必须大于等于当前时间"));
				return null;
			}
			BorrowApply apply=borrowService.getBorrowApply(borrow.getBorrowApplyId());
			//最小投资金额为空默认为50，最大投资金额为空默认为借款标填写金额
			/*if (borrow.getMin() == null || borrow.getMin()== 0) {
				borrow.setMin(50d);
			}else{
				if(borrow.getMin()<50 || borrow.getMin()%50 != 0){
					printJSON(new JsonMsg(12, "最小投标金额必须是50的整数倍"));
					return null;
				}
			}
			
			if (borrow.getMax() == null || borrow.getMax()== 0) {
				borrow.setMax(borrow.getAmount());
			}else{
				if(borrow.getMax()<borrow.getMin() && borrow.getMax()%borrow.getMin() != 0){
					printJSON(new JsonMsg(12, "最大投标金额必须大于最小投资金额,且是最小金额的整数倍"));
					return null;					
				}
			}*/
			if(borrow.getMin() == null){
				borrow.setMin(100.0);
			}
			if(borrow.getMax() == null){
				borrow.setMax(borrow.getAmount());
			}
			borrow.setCreateIp(request.getRemoteAddr());
			borrow.setNotPaymentFund(0.0);
			borrow.setNotPaymentTotal(0.0);
			borrow.setNotTenderMoney(borrow.getAmount());
			borrow.setPaymentFund(0.0);
			borrow.setPaymentInterest(0.0);
			borrow.setPaymentTotal(0.0);
			if("MONTH".equals(borrow.getDateUtil())){
				borrow.setPeriod(borrow.getDeadline());
			}else {
				borrow.setPeriod(1);
			}
			
			/*if("DAY".equals(borrow.getDateUtil())){
				int deadline = borrow.getDeadline();
				if(deadline % 30 != 0) {
					super.printJSON(new JsonMsg(1,"借款期限为天标的情况下请输入30的的倍数！"));
					return null;
				}
				borrow.setPeriod(deadline/30);
			}*/
			borrow.setSchedules(0.0);
			borrow.setNotPaymentInterest(0.0);
			borrow.setStatus(BorrowStatus.BORROW);
			borrow.setTenderMoney(0.0);
			if (borrow.getTimingShow() != null) {
				borrow.setCreateTime(borrow.getTimingShow());
				borrow.setExpireTime(DateUtils.getDayAfter(borrow.getTimingShow(), borrow.getExpire()));
				borrow.setVerfifyTime(borrow.getTimingShow());
			}else{
				borrow.setCreateTime(new Date());
				borrow.setExpireTime(DateUtils.getDayAfter(new Date(), borrow.getExpire()));
				borrow.setVerfifyTime(new Date());
			}
			borrow.setVerifyRemark("");
			borrow.setVerifyUser(getUserId());
			String code="";
			UUID uuid = UUID.randomUUID();
			code=code+uuid.toString().replaceAll("-", "").substring(0, 16);
			borrow.setCode(code);
			Integer id=borrowService.saveOrUpdateBorrow(borrow);
			
			if(id>0){
				//修改申请借款记录状态
				apply.setStatus(2);
				apply.setUse(borrow.getBorrowUse());
				borrowService.saveOrUpdateBorrowApply(apply);
		
				/**
				 * 开启自动投标
				 */
			/*
				if (borrow.getTimingShow() == null) {
					orderService.autoStart(borrow.getId());
				}
				//发标同时发布公告
				if(borrow.getTimingShow() != null){
					SimpleDateFormat time=new SimpleDateFormat("MM.dd—HH:mm");
					SimpleDateFormat time1 = new SimpleDateFormat("MM/dd");
					SimpleDateFormat time2 = new SimpleDateFormat("HH:mm");
					Article article = new Article();
					article.setTypeId(5);
					article.setTitle("新标预告"+"("+time.format(borrow.getTimingShow())+")");
					article.setStatus(1);
					article.setAuthor(((AdminUserVo)session.getAttribute("sysUser")).getUserName());
					article.setDesc(time1.format(borrow.getTimingShow())+borrow.getTitle()+"("+borrow.getDeadline()+"月)"+"年利率"+borrow.getPercent()+"%"
							+time2.format(borrow.getTimingShow()));
					article.setArticleOrder(1);
					article.setTags("公告");
					article.setContent("<div>"+time1.format(borrow.getTimingShow())+"&nbsp;"+borrow.getTitle()+""
							+"("+borrow.getDeadline()+"个月)"+"&nbsp;"+"年利率"+"&nbsp;"+borrow.getPercent()+"%"+
							"&nbsp"+"奖励年利率"+borrow.getRewardPercent()+"%"+"&nbsp"
							+"&nbsp"+time2.format(borrow.getTimingShow())+"</div>");
					article.setCreateIp(RequestUtil.getRemortIP(request));
					article.setCreateTime(new Date());
					article.setUpdateIp(RequestUtil.getRemortIP(request));
					article.setUpdateTime(new Date());
					articleService.saveOrUpdateArticle(article);
				}
				*/
			}	
			super.printJSON(new JsonMsg(-1,"操作成功",borrow));		
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
		
	}
	/**
	 * 修改标
	 * */
	@RequestMapping(value="/save",method=RequestMethod.POST)
	@ResponseBody
	public String saveBorrow(@RequestBody Borrow borrow) throws Exception{
		if(borrow.getStatus().equals("pay")) {
			if (getUserId() == null) {
				super.printJSON(new JsonMsg(0, "请先登录！"));
				return null;
			}
			if (StringUtils.isBlank(borrow.getLoanVisit())) {
				super.printJSON(new JsonMsg(1,"请输入贷后回访！"));
				return null;
			}
			Borrow b = borrowService.detailBorrow(borrow.getId());
			borrow.setLoanVisit(borrow.getLoanVisit());
			borrow.setPersonalInfo(b.getPersonalInfo());
			borrow.setCapitalInfo(b.getCapitalInfo());
			Integer id=borrowService.saveOrUpdateBorrow(borrow);
			if(id>0){
				super.printJSON(new JsonMsg(-1,"操作成功",borrow));
		
			}	
			return null;
			
		} else{
			try {
				if (getUserId() == null) {
					super.printJSON(new JsonMsg(0, "请先登录！"));
					return null;
				}
				if(StringUtil.isBlank(borrow.getTitle())){
					super.printJSON(new JsonMsg(1,"借款标题不能为空！"));
					return null;
				}
				if (borrow.getProductId() == null) {
					super.printJSON(new JsonMsg(1,"发标产品类型不能为空，请重新选择！"));
					return null;
				}
				/*if (StringUtils.isBlank(borrow.getBorrowUse())) {
					super.printJSON(new JsonMsg(1,"借款标用途不能为空！"));
					return null;
				}*/
				if (borrow.getAmount() == null || borrow.getAmount()<=0d) {
					super.printJSON(new JsonMsg(1,"借款金额输入错误，请重新输入！"));
					return null;
				}
				if (borrow.getAmount()%100 != 0) {
					super.printJSON(new JsonMsg(1,"借款金额输入错误，必须为100的倍数！"));
					return null;
				}
				if (borrow.getDeadline() == null) {
					super.printJSON(new JsonMsg(1,"借款期限不能为空，请重新输入！"));
					return null;
				}
				if (borrow.getPaymentMode() == null) {
					super.printJSON(new JsonMsg(1,"还款方式不能为空，请重新选择！"));
					return null;
				}
				/** 对还款方式的判断 **/
				if("DAY".equals(borrow.getDateUtil())) {
					if(borrow.getPaymentMode() != 1) {
						super.printJSON(new JsonMsg(1,"天标的还款方式能是一次性还款，请重新选择！"));
						return null;
					}
				}
				if (borrow.getPercent() == null) {
					super.printJSON(new JsonMsg(1,"借款标的年化收益率不能为空，请重新输入！"));
					return null;
				}
				/*if (borrow.getRewardPercent() != null) {
					if (borrow.getRewardPercent() >= borrow.getPercent()) {
						super.printJSON(new JsonMsg(1,"借款标的奖励年化收益率不能高于借款标的年化收益率，请重新输入！"));
						return null;
					}
				}*/
				if (borrow.getExpire() == null) {
					super.printJSON(new JsonMsg(1,"有效时间不能为空，请重新输入！"));
					return null;
				}
				/*if (StringUtils.isBlank(borrow.getAttachId())) {
					super.printJSON(new JsonMsg(1,"请上传借款标的材料！"));
					return null;
				}*/
	/*			if (StringUtils.isBlank(borrow.getAptitudeAttachId())) {
					super.printJSON(new JsonMsg(1,"请上传借款标的资质审核！"));
					return null;
				}*/
				/*if (StringUtils.isBlank(borrow.getDescr())) {
					super.printJSON(new JsonMsg(1,"请输入借款标项目介绍！"));
					return null;
				}*/
				/*
				if (StringUtils.isBlank(borrow.getWindControlDetail())) {
					super.printJSON(new JsonMsg(1,"请输入风控详情！"));
					return null;
				}*/
				
				if(borrow.getGuaranteeName() == null) {
					super.printJSON(new JsonMsg(1, "请输入借款标担保方！"));
					return null;
				}
				if (StringUtils.isBlank(borrow.getPersonalInfo())) {
					super.printJSON(new JsonMsg(1,"请上传个人信息！"));
					return null;
				}
				if (StringUtils.isBlank(borrow.getCapitalInfo())) {
					super.printJSON(new JsonMsg(1,"请上传资产信息！"));
					return null;
				}
				if (StringUtils.isBlank(borrow.getBorrowDetail())) {
					super.printJSON(new JsonMsg(1,"请输入借款标借入详情！"));
					return null;
				}
				if (StringUtils.isBlank(borrow.getCapitalVoucher())) {
					super.printJSON(new JsonMsg(1,"请输入借款标资产凭证！"));
					return null;
				}
				if(borrow.getTimingShow() != null && borrow.getTimingShow().getTime()<new Date().getTime()) {
					super.printJSON(new JsonMsg(1,"定时显示时间必须大于等于当前时间"));
					return null;
				}
				BorrowApply apply=borrowService.getBorrowApply(borrow.getBorrowApplyId());
				//最小投资金额为空默认为50，最大投资金额为空默认为借款标填写金额
				/*if (borrow.getMin() == null || borrow.getMin()== 0) {
					borrow.setMin(50d);
				}else{
					if(borrow.getMin()<50 || borrow.getMin()%50 != 0){
						printJSON(new JsonMsg(12, "最小投标金额必须是50的整数倍"));
						return null;
					}
				}
				
				if (borrow.getMax() == null || borrow.getMax()== 0) {
					borrow.setMax(borrow.getAmount());
				}else{
					if(borrow.getMax()<borrow.getMin() && borrow.getMax()%borrow.getMin() != 0){
						printJSON(new JsonMsg(12, "最大投标金额必须大于最小投资金额,且是最小金额的整数倍"));
						return null;					
					}
				}*/
				if(borrow.getMin() == null){
					borrow.setMin(100.0);
				}
				if(borrow.getMax() == null){
					borrow.setMax(borrow.getAmount());
				}
				borrow.setCreateIp(request.getRemoteAddr());
				borrow.setNotPaymentFund(0.0);
				borrow.setNotPaymentTotal(0.0);
				borrow.setNotTenderMoney(borrow.getAmount());
				borrow.setPaymentFund(0.0);
				borrow.setPaymentInterest(0.0);
				borrow.setPaymentTotal(0.0);
				if("MONTH".equals(borrow.getDateUtil())){
					borrow.setPeriod(borrow.getDeadline());
				}else {
					borrow.setPeriod(1);
				}
				
				/*if("DAY".equals(borrow.getDateUtil())){
					int deadline = borrow.getDeadline();
					if(deadline % 30 != 0) {
						super.printJSON(new JsonMsg(1,"借款期限为天标的情况下请输入30的的倍数！"));
						return null;
					}
					borrow.setPeriod(deadline/30);
				}*/
				borrow.setSchedules(0.0);
				borrow.setNotPaymentInterest(0.0);
				borrow.setStatus(BorrowStatus.BORROW);
				borrow.setTenderMoney(0.0);
				if (borrow.getTimingShow() != null) {
					borrow.setCreateTime(borrow.getTimingShow());
					borrow.setExpireTime(DateUtils.getDayAfter(borrow.getTimingShow(), borrow.getExpire()));
					borrow.setVerfifyTime(borrow.getTimingShow());
				}else{
					borrow.setCreateTime(new Date());
					borrow.setExpireTime(DateUtils.getDayAfter(new Date(), borrow.getExpire()));
					borrow.setVerfifyTime(new Date());
				}
				borrow.setVerifyRemark("");
				borrow.setVerifyUser(getUserId());
				String code="";
				UUID uuid = UUID.randomUUID();
				code=code+uuid.toString().replaceAll("-", "").substring(0, 16);
				borrow.setCode(code);
				Integer id=borrowService.saveOrUpdateBorrow(borrow);
				
				if(id>0){
					//修改申请借款记录状态
					apply.setStatus(2);
					apply.setUse(borrow.getBorrowUse());
					borrowService.saveOrUpdateBorrowApply(apply);
			
					/**
					 * 开启自动投标
					 */
				/*
					if (borrow.getTimingShow() == null) {
						orderService.autoStart(borrow.getId());
					}
					//发标同时发布公告
					if(borrow.getTimingShow() != null){
						SimpleDateFormat time=new SimpleDateFormat("MM.dd—HH:mm");
						SimpleDateFormat time1 = new SimpleDateFormat("MM/dd");
						SimpleDateFormat time2 = new SimpleDateFormat("HH:mm");
						Article article = new Article();
						article.setTypeId(5);
						article.setTitle("新标预告"+"("+time.format(borrow.getTimingShow())+")");
						article.setStatus(1);
						article.setAuthor(((AdminUserVo)session.getAttribute("sysUser")).getUserName());
						article.setDesc(time1.format(borrow.getTimingShow())+borrow.getTitle()+"("+borrow.getDeadline()+"月)"+"年利率"+borrow.getPercent()+"%"
								+time2.format(borrow.getTimingShow()));
						article.setArticleOrder(1);
						article.setTags("公告");
						article.setContent("<div>"+time1.format(borrow.getTimingShow())+"&nbsp;"+borrow.getTitle()+""
								+"("+borrow.getDeadline()+"个月)"+"&nbsp;"+"年利率"+"&nbsp;"+borrow.getPercent()+"%"+
								"&nbsp"+"奖励年利率"+borrow.getRewardPercent()+"%"+"&nbsp"
								+"&nbsp"+time2.format(borrow.getTimingShow())+"</div>");
						article.setCreateIp(RequestUtil.getRemortIP(request));
						article.setCreateTime(new Date());
						article.setUpdateIp(RequestUtil.getRemortIP(request));
						article.setUpdateTime(new Date());
						articleService.saveOrUpdateArticle(article);
					}
					*/
				}	
				super.printJSON(new JsonMsg(-1,"操作成功",borrow));		
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
			
		
		}
		
		
		
		
		
	}
	
	/**
	 * 编辑借款标
	 * @param borrow
	 * @return
	 */
	@RequestMapping(value="/updateBorrow",method=RequestMethod.POST)
	@ResponseBody
	public String updateBorrow(@RequestBody Borrow borrow) throws Exception{
		try {
			if (StringUtils.isBlank(borrow.getTitle())) {
				super.printJSON(new JsonMsg(1,"借款标题不能为空！"));
				return null;
			}
			if (StringUtils.isBlank(borrow.getBorrowUse())) {
				super.printJSON(new JsonMsg(1,"借款标用途不能为空！"));
				return null;
			}
			if (StringUtils.isBlank(borrow.getPersonalInfo())) {
				super.printJSON(new JsonMsg(1,"个人材料不能为空！"));
				return null;
			}
			
			if (StringUtils.isBlank(borrow.getCapitalInfo())) {
				super.printJSON(new JsonMsg(1,"资产材料不能为空！"));
				return null;
			}
			if (StringUtils.isBlank(borrow.getAttachId())) {
				super.printJSON(new JsonMsg(1,"请上传借款标的材料！"));
				return null;
			}
			if (StringUtils.isBlank(borrow.getAptitudeAttachId())) {
				super.printJSON(new JsonMsg(1,"请上传借款标的资质审核！"));
				return null;
			}
			if (StringUtils.isBlank(borrow.getDescr())) {
				super.printJSON(new JsonMsg(1,"请输入借款标项目介绍！"));
				return null;
			}
			Borrow br = borrowService.detailBorrow(borrow.getId());
			if (!br.getStatus().equals(BorrowStatus.BORROW)) {
				super.printJSON(new JsonMsg(1,"借款标状态不是投资中，保存失败！！"));
				return null;
			}
			if (br.getBorrowApplyId() != null && !br.getBorrowApplyId().equals(-1)) {
				BorrowApply apply=borrowService.getBorrowApply(br.getBorrowApplyId());
				apply.setUse(borrow.getBorrowUse());
				borrowService.saveOrUpdateBorrowApply(apply);
			}
			if (br.getTimingShow() != null && borrow.getTimingShow() != null && br.getExpire() != null) {
				//暂不限制，如果是编辑其他则此处限制有问题
//				if (DateUtils.getDistanceTimeNum(borrow.getTimingShow(), new Date())<=0) {
//					printJSON(new JsonMsg(1, "设定日期必须比当前日期晚！"));
//					return null;	
//				}
				borrow.setExpireTime(DateUtils.getDayAfter(borrow.getTimingShow(), br.getExpire()));
			}
			borrow.setUpdateIp(request.getRemoteAddr());
			borrow.setUpdateTime(new Date());
			Integer id=borrowService.saveOrUpdateBorrow(borrow);
			if(id>0){
				super.printJSON(new JsonMsg(-1,"操作成功！",id));
			}else{
				super.printJSON(new JsonMsg(0,"操作失败！",id));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}
	
	/**
	 * 复制借款标
	 * @param model
	 * @param borrowId 借款标id
	 * @throws Exception
	 */
	@RequestMapping(value="/copy",method=RequestMethod.GET)
	public String copyBorrow(Model model,@RequestParam(value="bid")Integer bid)throws Exception {
		BorrowVo borrowVo = borrowService.detailBorrowVo(bid);
		BorrowApplyVo borrowApply = borrowService.getBorrowApplyVo(borrowVo.getBorrowApplyId());
		List<BorrowGroup> borrowGroups = borrowService.listBorrowGroup();
		borrowVo.setBorrowUse(borrowApply.getUse());
		List<Product> productList = productService.productList();
		//清空复制标的定时显示时间
		borrowVo.setTimingShow(null);
		int expireDay = DateUtils.betweenDays(borrowVo.getCreateTime(), borrowVo.getExpireTime());
		model.addAttribute("expireDay", expireDay);
		model.addAttribute("item", borrowApply);
		model.addAttribute("model", borrowVo);
		model.addAttribute("borrowGroups", borrowGroups);
		model.addAttribute("productList", productList);
		model.addAttribute("guaranteeAll", Borrow.guaranteeAll);
		return "/admin/borrow/AddBorrowView";
	}
	
	/**
	 * 借款标管理
	 * @param model
	 * @param index 当前页数
	 * @param limit 每页条数
	 * @param status 借款标状态
	 * @param createTimeBegin 借款标创建时间，开始
	 * @param createTimeEnd 借款标创建时间，结束
	 * @return
	 */
	@RequestMapping("/list")
	public String listBorrow(Model model,
			   @RequestParam(value="index",required=false,defaultValue="1") int index,
			   @RequestParam(value="limit",required=false,defaultValue="10") int limit,
			   @RequestParam(value="status",required=false)String status,
			   @RequestParam(value="createTimeBegin",required=false)String createTimeBegin,
			   @RequestParam(value="createTimeEnd",required=false)String createTimeEnd,
			   @RequestParam(value="borrow_title",required=false) String borrow_title) throws Exception{
		BorrowVo borrowVo = new BorrowVo();
		borrowVo.setIndex(index);
		borrowVo.setLimit(limit);
		if (StringUtils.isNotBlank(status)) {
			borrowVo.setStatus(status);
			model.addAttribute("status", status);
		}
		if (StringUtils.isNotBlank(createTimeBegin)) {
			borrowVo.setCreateTimeBegin(DateUtils.getRealDate(DateUtils.convert(createTimeBegin, DateUtils.YEAR_MOUTH_DAY_FORMAT)));
			model.addAttribute("createTimeBegin", createTimeBegin);
		}
		if (StringUtils.isNotBlank(createTimeEnd)) {
			borrowVo.setCreateTimeEnd(DateUtils.getFullDate(DateUtils.convert(createTimeEnd, DateUtils.YEAR_MOUTH_DAY_FORMAT)));
			model.addAttribute("createTimeEnd", createTimeEnd);
		}
		if (StringUtils.isNotBlank(borrow_title)) {
			borrow_title=java.net.URLDecoder.decode(borrow_title , "UTF-8");
			borrowVo.setTitle(borrow_title);
			model.addAttribute("borrow_title", borrow_title);
		}
		PageInfo<BorrowVo> pageInfo = borrowService.listBorrow(borrowVo);
		model.addAttribute("pageInfo", pageInfo);
		List<Product> productList = productService.productList();
		model.addAttribute("productList", productList);
		return ftl(Thread.currentThread().getStackTrace());
	}
	
	/**
	 * 借款标详情
	 * @param model
	 * @param borrowId 借款标id
	 * @return
	 * @throws ParseException 
	 */
	@RequestMapping(value="/detailBorrow",method=RequestMethod.GET)
	public String detailBorrow(Model model,@RequestParam Integer borrowId) throws ParseException {
		BorrowVo borrowVo = borrowService.detailBorrowVo(borrowId);
		BorrowApplyVo borrowApplyVo = borrowService.getBorrowApplyVo(borrowVo.getBorrowApplyId());
		if (borrowApplyVo != null) {
			//model.addAttribute("borrowApplyUserName", borrowApplyVo.getUserName());
			//model.addAttribute("borrowApplyRealName", borrowApplyVo.getRealName());
			model.addAttribute("item", borrowApplyVo);
			borrowVo.setBorrowUse(borrowApplyVo.getUse());
		}
		if(borrowVo != null && borrowVo.getPersonalInfo() != null) {//个人信息图片
			List<ResourceVo> personalInfo = resourceService.getResourcesById(borrowVo.getPersonalInfo());
			model.addAttribute("personalList", personalInfo);
		}
		if(borrowVo != null && borrowVo.getCapitalInfo() != null) {//资产信息图片
			List<ResourceVo> capitalInfo = resourceService.getResourcesById(borrowVo.getCapitalInfo());
			model.addAttribute("capitalList", capitalInfo);
		}
		borrowVo.setBorrowDetail(borrowVo.getBorrowDetail().replaceAll("\r", "").replaceAll("\t", "").replaceAll("\n", ""));
		model.addAttribute("model", borrowVo);
		List<BorrowGroup> borrowGroups = borrowService.listBorrowGroup();
		model.addAttribute("borrowGroups", borrowGroups);
		//标的有效期
		int expireDay = DateUtils.betweenDays(borrowVo.getCreateTime(), borrowVo.getExpireTime());
		model.addAttribute("expireDay", expireDay);
		//产品类型+担保方
		List<Product> productList = productService.productList();
		model.addAttribute("productList", productList);
		model.addAttribute("guaranteeAll", Borrow.guaranteeAll);
		return ftl(Thread.currentThread().getStackTrace());
	}
	/**
	 * 新手借款标管理
	 * @param model
	 * @param index
	 * @param limit
	 * @param status
	 * @return
	 */
	@RequestMapping("/listNewBorrow")
	public String listNewBorrow(Model model,
			   @RequestParam(value="index",required=false,defaultValue="1") int index,
			   @RequestParam(value="limit",required=false,defaultValue="10") int limit,
			   @RequestParam(value="status",required=false)String status){
		BorrowVo borrowVo = new BorrowVo();
		borrowVo.setIndex(index);
		borrowVo.setLimit(limit);
		borrowVo.setBorrowApplyId(-1);
		PageInfo<BorrowVo> pageInfo = borrowService.listNewBorrow(borrowVo);
		if (CollectionUtils.isNotEmpty(pageInfo.getPageList())) {
			for (BorrowVo vo : pageInfo.getPageList()) {
				if (vo.getAmount().equals(vo.getTenderMoney())) {
					//获取新手标还款信息
					List<BorrowPaymentVo> borrowPayments = borrowPaymentService.getBorrowPaymentByBorrowId(vo.getId());
					if (borrowPayments != null && borrowPayments.size() == 1) {
						vo.setPaymentTime(borrowPayments.get(0).getExpectDate());
					}
				}
			}
		}
		model.addAttribute("pageInfo", pageInfo);
		return ftl(Thread.currentThread().getStackTrace());
	}
	
	/**
	 * 删除图片
	 * @param flag 
	 * @param x  标id
	 * @param y  文件id
	 * @throws Exception
	 */
	@RequestMapping(value="/file/delete",method=RequestMethod.POST)
	public void deleteResource(@RequestParam(value="f", required=true)String f,
			@RequestParam(value="x", required=true)String x,
			@RequestParam(value="y", required=true)String y
			) throws Exception {	
		
		
		//借款标id
		Integer borrowId = Integer.parseInt(x.toString());
		Borrow borrow = borrowService.detailBorrow(borrowId);
		String[] arr = null;		
		Integer flag = 0;
		Integer flag1 = 0;
		if("3".equals(f)) { //对个人信息操作
			String personId = y.toString();
			if(personId == null) {
				printJSON(new JsonMsg(0, "删除失败！"));
			}
			//Integer personId_int = Integer.parseInt(personId);
			arr = borrow.getPersonalInfo().split(",");			
			String result = arrToString(arr,personId);
			borrow.setPersonalInfo(result);
		    flag1 = fileContrller.deleteResource(personId);
		} else if("4".equals(f)) { //对资产信息操作
			String fundId = y.toString();
			if(fundId == null) {
				printJSON(new JsonMsg(0, "删除失败！"));
			}
			//Integer fundId_int = Integer.parseInt(fundId);
			arr = borrow.getCapitalInfo().split(",");
			String result = arrToString(arr,fundId);
			borrow.setCapitalInfo(result);
		    flag1 = fileContrller.deleteResource(fundId);
		}
		flag = borrowService.saveOrUpdateBorrow(borrow);
		if (flag >0 && flag1 > 0) {
			printJSON(new JsonMsg(-1, "删除成功！"));	
		}else{
			printJSON(new JsonMsg(0, "删除失败！"));
		}
		
	}
	/**
	 * 删除图片工具
	 * @param arr
	 * @param id
	 * @return
	 */
	public String arrToString(String[] arr,String id) {
		String[] tempArr = new String[arr.length];
		int i = 0;
		for(String s : arr) {
			if(!id.equals(arr[i])) {
				tempArr[i]=s;
			}
			i++;			
		}
		String result="";
		for(int j=0 ;j<tempArr.length ;j++) {
			if(j<tempArr.length-1 && tempArr[j] != null) {
				result += "," + tempArr[j];
			} else if(tempArr[j] != null) {
				result = result + tempArr[j];
			}
		}
		
		return result;
	}
	
	
	/**
	 * 新手标还款
	 * @param borrowId
	 * @throws Exception
	 */
	@RequestMapping(value="/newBorrowpayment",method=RequestMethod.POST)
	public void newBorrowpayment(@RequestParam Integer borrowId) throws Exception{
		try{
			//注意：新手标无借款用户，属于后台发标
//			UserAccount userAccount = userAccountService.getByUserId(userId);
			BorrowPaymentVo borrowPaymentVo = new BorrowPaymentVo();
			borrowPaymentVo.setBorrowId(borrowId);
//			borrowPaymentVo.setUserId(userId);
			List<BorrowPaymentVo> paymentVos = borrowPaymentService.borrowUserRepayList(borrowPaymentVo);
			if (paymentVos == null || paymentVos.size() == 0 || paymentVos.size() >1) {
				printJSON(new JsonMsg(0, "还款失败，数据异常！"));
				return;
			}
			BorrowPaymentVo paymentVo = paymentVos.get(0);
//			if (userAccount == null || userAccount.getBalance() == null || userAccount.getBalance()<=0d || userAccount.getBalance()<paymentVo.getNotPaymentTotal()) {
//				printJSON(new JsonMsg(1, "还款失败！可用余额不足，请先充值！"));
//				return;
//			}
			Integer i = borrowPaymentService.payment(paymentVo.getId());
			if (i >0) {
				printJSON(new JsonMsg(-1, "还款成功！"));
			}else{
				printJSON(new JsonMsg(0, "还款失败！"));
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 新手标截标
	 * @param model
	 * @param borrowId 借款标id
	 */
	@RequestMapping(value="/new/intercept",method = RequestMethod.POST)
	public void interceptNewBorrow(Model model,@RequestParam(value="borrowId")int borrowId) throws Exception{
		try {
			Borrow borrow = borrowService.detailBorrow(borrowId);
			if (borrow == null) {
				printJSON(new JsonMsg(1, "新手标截标失败"));
				return;
			}
			if (!borrow.getStatus().equals(BorrowStatus.NEW) && !borrow.getStatus().equals(BorrowStatus.BORROW)) {
				printJSON(new JsonMsg(2, "借款标状态不是投资中，截标失败"));
				return;
			}
			if (borrow.getTenderMoney() == null || borrow.getTenderMoney().equals(0d)) {
				printJSON(new JsonMsg(3, "已投资金额为0，截标失败"));
				return;
			}
			borrow.setAmount(borrow.getTenderMoney());
			borrow.setSchedules(100d);
			borrow.setStatus(BorrowStatus.CHECK);
			borrow.setNotTenderMoney(0d);//未投金额重置为0
			Integer i = borrowService.saveOrUpdateBorrow(borrow);
			if (i>0) {
				printJSON(new JsonMsg(-1, "截标成功！"));
			}else{
				printJSON(new JsonMsg(0, "截标失败！"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 私有借款标管理
	 * @param model
	 * @param index
	 * @param limit
	 * @return
	 */
	@RequestMapping("/private/list")
	public String listPrivateBorrow(Model model,
			   @RequestParam(value="index",required=false,defaultValue="1") int index,
			   @RequestParam(value="limit",required=false,defaultValue="10") int limit){
		BorrowVo borrowVo = new BorrowVo();
		borrowVo.setIndex(index);
		borrowVo.setLimit(limit);
		borrowVo.setPrivateBorrowGroup("Y");
		PageInfo<BorrowVo> pageInfo = borrowService.listBorrow(borrowVo);
		model.addAttribute("pageInfo", pageInfo);
		return ftl(Thread.currentThread().getStackTrace());
	}
	
	/**
	 * 设置私有标用户组
	 * @param model
	 * @param index
	 * @param limit
	 * @return
	 */
	@RequestMapping("/settingBorrowGroupUser")
	public String settingBorrowGroupUser(Model model,Integer borrowGroupId){
		model.addAttribute("borrowGroupId", borrowGroupId);
		//借款标组下的用户
		List<BorrowGroupUserVo> borrowGroupUsers = borrowService.getUserByBorrowGroupId(borrowGroupId);
		model.addAttribute("borrowGroupUsers", borrowGroupUsers);
		//所有的用户
		User user = new User();
		List<User> users = userService.getByUser(user);
		model.addAttribute("users", users);
		return ftl(Thread.currentThread().getStackTrace());
	}
	
	/**
	 * 分页查看借款标组下的用户
	 * @param model
	 * @param borrowGroupId
	 * @param index
	 * @param limit
	 * @return
	 */
	@RequestMapping("/showPrivateBorrowDetail")
	public String showPrivateBorrowDetail(Model model,
									   @RequestParam(value="borrowGroupId")Integer borrowGroupId,  
									   @RequestParam(value="index",required=false,defaultValue="1") int index,
									   @RequestParam(value="limit",required=false,defaultValue="10") int limit){
		BorrowGroupUserVo borrowGroupUserVo = new BorrowGroupUserVo();
		borrowGroupUserVo.setIndex(index);
		borrowGroupUserVo.setLimit(limit);
		borrowGroupUserVo.setBorrowGroupId(borrowGroupId);
		PageInfo<BorrowGroupUserVo> pageInfo = borrowService.getBorrowGroupUsers(borrowGroupUserVo);
		model.addAttribute("pageInfo", pageInfo);
		model.addAttribute("borrowGroupId", borrowGroupId);
		return ftl(Thread.currentThread().getStackTrace());
	}
	
	/**
	 * 特殊借款标组管理
	 * @param model
	 * @return
	 */
	@RequestMapping("/listBorrowGroup")
	public String listBorrowGroup(Model model){
		List<BorrowGroup> list = borrowService.listBorrowGroup();
		model.addAttribute("list", list);
		return ftl(Thread.currentThread().getStackTrace());
	}
	
	/**
	 * 保存特殊借款标组用户
	 * @param borrowGroupId
	 * @param users
	 */
	@RequestMapping("/saveBorrowGroupUsers")
	public void saveBorrowGroupUsers(@RequestParam Integer borrowGroupId,@RequestParam(required=false) String users) {
		if (borrowGroupId == null) {
			return;
		}
		Integer bid = borrowService.deleteBorrowGroupUsers(borrowGroupId);
		String[] userIds = {};
		if (StringUtils.isNotBlank(users)) {
			userIds = users.split(",");
		}
		List<BorrowGroupUser> borrowGroupUsers = new ArrayList<BorrowGroupUser>();
		List<User> userList = new ArrayList<User>();
		if (userIds != null && userIds.length >0) {
			for (String userId : userIds) {
				BorrowGroupUser borrowGroupUser = new BorrowGroupUser();
				borrowGroupUser.setBorrowGroupId(borrowGroupId);
				borrowGroupUser.setUserId(Integer.valueOf(userId));
				borrowGroupUser.setCreateTime(new Date());
				borrowGroupUsers.add(borrowGroupUser);
				User user = new User();
				user.setId(Integer.valueOf(userId));
				user.setIsSpecial("Y");
				userList.add(user);
			}
		}
		try {
			Integer i = 0;
			if (CollectionUtils.isNotEmpty(borrowGroupUsers)) {
				i = borrowService.save(borrowGroupUsers);
				userService.batchUpdate(userList);
			}
			if (bid > 0 || i > 0) {
				printJSON(new JsonMsg(-1, "保存成功"));
			}else{
				printJSON(new JsonMsg(0, "保存失败"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 债权转让所有列表
	 * @param model
	 * @return
	 */
	@RequestMapping("/change/list")
	public String listChange(Model model,
			   @RequestParam(value="index",required=false,defaultValue="1") int index,
			   @RequestParam(value="limit",required=false,defaultValue="10") int limit){
		ChangeVo changeVo = new ChangeVo();
		PageInfo<ChangeVo> pageInfo=changeService.listChange(index, limit,changeVo);
		model.addAttribute("pageInfo",pageInfo);
		return ftl(Thread.currentThread().getStackTrace());
	}
	
	/**
	 * 债权转让记录列表
	 * @param model
	 * @return
	 */
	@RequestMapping("/changeRecord/list")
	public String listChangeRecord(Model model,@RequestParam(value="changeId") Integer changeId){
		List<ChangeRecord> list =changeService.listByChangeId(changeId);
		model.addAttribute("list",list);
		return ftl(Thread.currentThread().getStackTrace());
	}
	
	/**
	 * 发布债权转让
	 * @param change
	 * @return
	 */
	@RequestMapping("/change/add")
	@ResponseBody
	public String addChange(@RequestBody Change change){
		try {
			changeService.saveOrUpdateChange(change);
			super.printJSON(new JsonMsg(-1, "操作成功"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 债权竞拍
	 * @param record
	 * @return
	 */
	@RequestMapping("/change/record/add")
	@ResponseBody
	public String addChangeRecord(@RequestBody ChangeRecord record){
		try {
			changeService.saveOrUpdateRecord(record);
			super.printJSON(new JsonMsg(-1, "操作成功"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;	
	}
	
	/**
	 * 还款
	 * @param pid 还款记录id
	 * @param index 还款期数
	 * @return
	 */
	@RequestMapping("/payment")
	public String payment(@RequestParam("pid") Integer pid,
			              @RequestParam("borrowId") Integer borrowId,
			              @RequestParam("userId") Integer userId){
		try {
			BorrowPaymentVo payment=borrowPaymentService.detail(pid);
			if(checkPayment(borrowId,userId,payment.getPeriodIndex())){
				borrowPaymentService.payment(borrowId);
			}
			super.printJSON(new JsonMsg(-1, "操作成功"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 根据paymentId和还款期数检查该期数之前的还款状态
	 * @param paymentId 
	 * @param index 还款当期
	 * @return
	 */
	public boolean checkPayment(Integer borrowId,Integer userId,Integer index){
		if(index==1){
			return true;
		}else{
			if(index>1){
				BorrowPaymentVo borrowPaymentVo = new BorrowPaymentVo();
				borrowPaymentVo.setUserId(userId);
				borrowPaymentVo.setBorrowId(borrowId);
				borrowPaymentVo.setPeriodIndex(index--);
				List<BorrowPaymentVo> paymentList = borrowPaymentService.borrowUserRepayList(borrowPaymentVo);
				
				if("Y".equals(paymentList.get(0).getStatus())){
					return true;
				}else{
					return false;
				}
			}	
		}
		return false;
	}
	
	
	
	/**
	 * 后台发布新手标
	 * @return
	 */
	@RequestMapping("/new")
	public String newView(){
		return ftl(Thread.currentThread().getStackTrace());
	}
	
	/**
	 * 发布新手标
	 * @param borrow
	 * @return
	 */
	@RequestMapping("/new/save")
	@ResponseBody
	public String saveNewBorrow(@RequestBody Borrow borrow){
		try {
			if (getUserId() == null) {
				super.printJSON(new JsonMsg(0, "请先登录！"));
				return null;
			}
			if(StringUtil.isBlank(borrow.getTitle())){
				super.printJSON(new JsonMsg(1,"借款标题不能为空！"));
				return null;
			}
//			if (StringUtils.isBlank(borrow.getAssuranceProvider())) {
//				super.printJSON(new JsonMsg(1,"担保方不能为空！"));
//				return null;
//			}
			if (borrow.getAmount() == null || borrow.getAmount()<=0d) {
				super.printJSON(new JsonMsg(1,"借款金额输入错误，请重新输入！"));
				return null;
			}
			if (borrow.getDeadline() == null) {
				super.printJSON(new JsonMsg(1,"借款期限不能为空，请重新输入！"));
				return null;
			}
			if (borrow.getPaymentMode() == null) {
				super.printJSON(new JsonMsg(1,"还款方式不能为空，请重新选择！"));
				return null;
			}
			if (borrow.getPercent() == null) {
				super.printJSON(new JsonMsg(1,"借款标的年化收益率不能为空，请重新输入！"));
				return null;
			}
			if (borrow.getMin() == null) {
				super.printJSON(new JsonMsg(1,"借款标的最小投资金额不能为空，请重新输入！"));
				return null;
			}
			if (borrow.getMax() == null) {
				super.printJSON(new JsonMsg(1,"借款标的最大投资金额不能为空，请重新输入！"));
				return null;
			}
			if (borrow.getTimingShow() != null) {
				if (DateUtils.getDistanceTimeNum(borrow.getTimingShow(), new Date())<=0) {
					printJSON(new JsonMsg(1, "设定日期必须必当前日期晚！"));
					return null;	
				}
			}
			
			borrow.setBorrowApplyId(-1);
			borrow.setCreateIp(request.getRemoteAddr());
			borrow.setDateUtil("DAY");
			borrow.setNotPaymentFund(0.0);
			borrow.setNotPaymentTotal(0.0);
			borrow.setNotTenderMoney(borrow.getAmount());
			borrow.setPaymentFund(0.0);
			borrow.setPaymentInterest(0.0);
			borrow.setPaymentTotal(0.0);
			borrow.setPeriod(borrow.getDeadline());
			borrow.setSchedules(0.0);
			borrow.setNotPaymentInterest(0.0);
			borrow.setStatus(BorrowStatus.NEW);
			borrow.setTenderMoney(0.0);
			if (borrow.getTimingShow() != null) {
				borrow.setCreateTime(borrow.getTimingShow());
				borrow.setVerfifyTime(borrow.getTimingShow());
			}else{
				borrow.setCreateTime(new Date());
				borrow.setVerfifyTime(new Date());
			}
			borrow.setVerifyRemark("");
			borrow.setVerifyUser(getUserId());
//			Borrow lastBorrow = borrowService.lastBorrow();
//			if (lastBorrow != null) {
//				//TODO
//			}
			Integer id=borrowService.saveOrUpdateBorrow(borrow);
			//发标同时发布公告
			if(borrow.getTimingShow() != null){
				SimpleDateFormat time=new SimpleDateFormat("MM.dd—HH:mm");
				SimpleDateFormat time1 = new SimpleDateFormat("MM/dd");
				SimpleDateFormat time2 = new SimpleDateFormat("HH:mm");
				Article article = new Article();
				article.setTypeId(5);
				article.setTitle("新标预告"+"("+time.format(borrow.getTimingShow())+")");
				article.setStatus(1);
				article.setAuthor(((AdminUserVo)session.getAttribute("sysUser")).getUserName());
				article.setDesc(time1.format(borrow.getTimingShow())+borrow.getTitle()+"("+borrow.getDeadline()+"天)"+"年利率"+borrow.getPercent()+"%"
						+time2.format(borrow.getTimingShow()));
				article.setArticleOrder(1);
				article.setTags("公告");
				article.setContent("<div>"+time1.format(borrow.getTimingShow())+"&nbsp;"+borrow.getTitle()+""
						+"("+borrow.getDeadline()+"天)"+"&nbsp;"+"年利率"+"&nbsp;"+borrow.getPercent()+"%"+"&nbsp"
						+time2.format(borrow.getTimingShow())+"</div>");
				article.setCreateIp(RequestUtil.getRemortIP(request));
				article.setCreateTime(new Date());
				article.setUpdateIp(RequestUtil.getRemortIP(request));
				article.setUpdateTime(new Date());
				articleService.saveOrUpdateArticle(article);
			}
			super.printJSON(new JsonMsg(-1,"操作成功",id));
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;		
	}
	
	/**
	 * 流标
	 * @param borrowId 标id
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/cancel")
	public String borrowCancel(@RequestParam("borrowId") Integer borrowId) throws Exception{
		Borrow borrow=borrowService.getBorrowById(borrowId);
		if(!"borrow".equals(borrow.getStatus())){
			super.printJSON(new JsonMsg(1,"该标不能发生流标"));
			return null;
		}
		super.printJSON(new JsonMsg(-1,"操作成功"));
		return null;
	}
	
	/**
	 * 到时修改标状态
	 * @param borrowId
	 * @throws Exception 
	 */
	@RequestMapping("/update")
	public void borrowUpdate(@RequestParam("borrowId") Integer borrowId) throws Exception{
		Borrow borrow = borrowService.getBorrowById(borrowId);
		borrow.setStatus(BorrowStatus.BORROW);
		int i = borrowService.saveOrUpdateBorrow(borrow);
		if(i>0){
			super.printJSON(new JsonMsg(-1, "操作成功！"));		
		}			
		
	}
}
